<template>
  <div>
    <el-page-header
      v-if="!productId"
      icon=""
      title="产品管理"
      content="添加产品"
    />
    <el-page-header
      v-else
      title="产品管理"
      content="编辑产品"
      @back="handleBack()"
    />

    <el-card style="margin-top: 20px">
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productFormRules"
        label-width="120px"
        class="demo-ruleForm"
        v-if="loaded"
      >
        <!-- 产品名称 -->
        <el-form-item label="产品名称" prop="title">
          <el-input v-model="productForm.title" />
        </el-form-item>

        <!-- 产品图片 -->
        <el-form-item label="产品图片" prop="cover">
          <Upload :avatar="productForm.cover" @imgChange="handleUploadChange" />
        </el-form-item>

        <!-- 产品简要描述 -->
        <el-form-item label="产品简要描述" prop="introduction">
          <el-input
            v-model="productForm.introduction"
            type="textarea"
            :autosize="{ minRows: 4 }"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>

        <!-- 产品详细描述 -->
        <el-form-item label="产品详细描述" prop="detail">
          <el-input
            v-model="productForm.detail"
            type="textarea"
            :autosize="{ minRows: 4 }"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <!-- 添加/编辑产品 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
  
  <script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import Upload from "@/components/upload/Upload.vue";
import upload from "@/utils/upload";

const router = useRouter(); // 获取'全局的路由实例'
const route = useRoute(); // 获取'当前路由的状态'
const loaded = ref(false); // 页面数据是否加载完毕, 【true: 加载完毕; false: 加载中】

const productFormRef = ref();
const productForm = reactive({
  title: "", //产品名称
  introduction: "", //简要描述
  detail: "", //详细描述
  cover: "/images/defaultUserImg.png",
  file: null,
});
// 表单校验
const productFormRules = reactive({
  title: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  introduction: [
    { required: true, message: "请输入简要描述", trigger: "blur" },
  ],
  detail: [{ required: true, message: "请输入详细描述", trigger: "blur" }],
  cover: [{ required: true, message: "请上传产品图片", trigger: "blur" }],
});

// 每次选择完图片之后的回调
const handleUploadChange = (file) => {
  productForm.cover = URL.createObjectURL(file);
  productForm.file = file;
};

/**
 * 编辑页面
 * */
const productId = ref(route.params?.productId || null);
// 获取产品详情信息
const getDetailData = async () => {
  await axios
    .get(`/adminapi/product/list/${productId.value}`)
    .then((res) => {
      Object.assign(productForm, res.data.data[0]);
    })
    .catch((error) => {
      console.error(error);
    });
  loaded.value = true;
};
// 后退
const handleBack = () => {
  router.back();
};

// 添加/编辑产品的提交
const submitForm = () => {
  productFormRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!productId.value) {
      await upload("/adminapi/product/add", productForm);
      router.push(`/product-manage/productlist`);
    } else {
      const params = new FormData();
      for (let i in productForm) {
        params.append(i, productForm[i]);
      }
      await axios
        .put(`/adminapi/product/list/${productId.value}`, params)
        .catch(() => {
          console.error(error);
        });
      router.back();
    }
  });
};

// 组件挂载后执行的钩子函数
onMounted(() => {
  if (productId.value) {
    getDetailData();
  } else {
    loaded.value = true;
  }
});
</script>
  
<style lang="scss" scoped>
.el-form {
  margin-top: 20px;
}
</style>
  